<template>
  <div :class="['chat-header', !isPC && 'chat-header-h5']">
    <div v-if="!isPC && isNotRoomChat" :class="['chat-header-back', !isPC && 'chat-header-h5-back']"
      @click="closeChat(currentConversation.conversationID)">
      <Icon :file="backSVG" />
    </div>
    <div class="chat-header-container" style="flex: 1;">
      <div v-if="isNotRoomChat" :class="['chat-header-content', !isPC && 'chat-header-h5-content']"
        style="display: flex;">
        <div style="display: flex; align-items: center; flex: 1; flex-wrap: wrap;">
          <div>{{ currentConversationName }}</div>
          <div style="color: #ff0000;" v-if="groupInfo.chat_group_status == 0">（已过期）</div>
          <!-- <el-tag type="success" effect="dark" style="margin-left: 10px;" v-if="groupInfo.user_vip_name">{{ groupInfo.user_vip_name }}</el-tag> -->
          <!-- <el-tag type="primary" effect="dark" style="margin-left: 10px;">{{ groupInfo.channel_name }}</el-tag> -->
        </div>
        <!-- <div style="display: flex; align-items: center; flex-wrap: wrap;" v-if="!isNotInGroup">
          <el-tag type="danger" effect="dark" style="margin-left: 10px;" v-for="(item, index) in tags" :key="index"
            closable @close="handleDelTag(index)">{{
            item.name }}</el-tag>
        </div> -->

      </div>
      <div>
        <!-- <JoinGroupCard v-if="isPC" /> -->
      </div>
    </div>
    <div :class="['chat-header-setting', !isPC && 'chat-header-h5-setting']">
      <!-- <div v-for="(item, index) in props.headerExtensionList" :key="index" @click.stop="handleExtensions(item)">
        <Icon :file="item.icon" />
      </div> -->
      <el-icon size="18" style="cursor: pointer;" @click.stop="handleExtensions" v-if="!isNotInGroup">
        <MoreFilled />
      </el-icon>
    </div>
    <el-drawer v-model="drawer" :with-header="false" size="450px">
      <div class="drawer-header">
        <el-icon size="18" style="float: right; cursor: pointer;" @click="drawer = false">
          <CloseBold />
        </el-icon>
        <div class="title">群管理</div>
      </div>
      <div class="row">
        <div class="title">群名称</div>
        <div class="content">{{ groupInfoManager.chat_group_name }}</div>
      </div>
      <div class="row">
        <div class="title">
          <span>群成员</span>
          <div class="title-right" @click="openInnerDrawer(1)" style="cursor: pointer;">
            <div>{{ groupInfoManager.memberNum }}人</div>
            <el-icon size="14" style="cursor: pointer; color: #666;">
              <ArrowRight />
            </el-icon>
          </div>
        </div>
        <div class="content">
          <div class="member-list">
            <template v-for="(item, index) in groupInfoManager.member" :key="index">
              <div class="member-item" v-if="index < 7">
                <img :src="item.avatar" />
                <span>{{ item.user_name }}</span>
              </div>
            </template>
            <!-- <div class="add-member" @click="openAddMember">
              <el-icon>
                <Plus />
              </el-icon>
            </div> -->
          </div>
        </div>
      </div>
      <!-- <div class="row">
        <div class="title">
          <span>群公告</span>
          <div class="title-right" @click="openInnerDrawer(2)">
            <el-icon size="14" style="cursor: pointer; color: #666;">
              <ArrowRight />
            </el-icon>
          </div>
        </div>
      </div> -->
      <div class="row">
        <div class="title">
          <span>群介绍</span>
          <div class="title-right" @click="openInnerDrawer(3)">
            <el-icon size="14" style="cursor: pointer; color: #666;">
              <ArrowRight />
            </el-icon>
          </div>
        </div>
      </div>
      <div class="row">
        <div class="title">
          <span>群备注</span>
          <div class="title-right" @click="openInnerDrawer(4)">
            <el-icon size="14" style="cursor: pointer; color: #666;">
              <ArrowRight />
            </el-icon>
          </div>
        </div>
      </div>
      <div class="row">
        <div class="title">
          <span>群ID</span>
          <div class="title-right">
            {{ groupInfoManager.GroupId }}
          </div>
        </div>
      </div>
      <div class="row">
        <div class="title">
          <span>群绑定手机号</span>
          <div class="title-right" style="color: #ff0000;">
            {{ groupInfoManager.chat_group_phone }}
          </div>
        </div>
      </div>
      <div class="row">
        <div class="title">
          <span>建群时间</span>
          <div class="title-right" style="color: #ff0000;">
            {{ groupInfoManager.create_time }}
          </div>
        </div>
      </div>
      <div class="row">
        <div class="title">
          <span>开始服务时间</span>
          <div class="title-right" style="color: #ff0000;">
            {{ groupInfoManager.create_time }}
          </div>
        </div>
      </div>
      <div class="row">
        <div class="title">
          <span>服务到期时间</span>
          <div class="title-right" style="color: #ff0000;">
            {{ groupInfoManager.group_end_time }}
          </div>
        </div>
      </div>
      <el-drawer v-model="innerDrawer" :title="innerTitle" :append-to-body="true" :modal="false" size="450px">
        <div v-if="innerTitle == '群成员'">
          <el-card>
            <template #header>
              <div class="card-header">
                <span style="font-size: 16px;">用户</span>
              </div>
            </template>
            <ul class="member-list">
              <template v-for="(item, index) in groupInfoManager.member">
                <li :key="index" v-if="item.user_type == 1">
                  <img :src="item.avatar" />
                  <div>{{ item.user_name }}<span v-if="item.f_user_id == Number(userInfo.id)">（我）</span></div>
                </li>
              </template>
            </ul>
          </el-card>
          <el-card style="margin-top: 10px;">
            <template #header>
              <div class="card-header">
                <span style="font-size: 16px;">咨询组成员</span>
              </div>
            </template>
            <ul class="member-list">
              <template v-for="(item, index) in groupInfoManager.member">
                <li :key="index" v-if="item.user_type == 2" @click="openUserProfile(item)">
                  <img :src="item.avatar" />
                  <div>{{ item.user_name }}<span v-if="item.f_user_id == Number(groupInfoManager.owner_id)">（群主）</span>
                  </div>
                </li>
              </template>
            </ul>
          </el-card>
        </div>
        <div v-if="innerTitle == '群介绍'">
          <div class="drawer-content">{{ groupInfoManager.Introduction }}</div>
        </div>
        <div v-if="innerTitle == '群备注'">
          <div class="drawer-content">{{ groupInfoManager.note }}</div>
        </div>
      </el-drawer>
    </el-drawer>

    <el-dialog v-model="dialogVisible" title="添加群成员" width="700">
      <el-form label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="类型：">
              <el-radio-group v-model="memberType" @change="onTypeChange">
                <el-radio :value="2">法务</el-radio>
                <el-radio :value="1">用户</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="姓名：">
              <el-input placeholder="请输入姓名" v-model="queryName" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="手机：">
              <el-input placeholder="请输入手机" v-model="queryMobile" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item>
              <el-button type="primary" @click="onSearch">搜索</el-button>
              <el-button @click="onClearSearch">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div v-if="memberType == 2">
        <el-table :data="legalList" border style="width: 100%">
          <el-table-column prop="user_name" label="姓名" />
          <el-table-column prop="user_phone" label="手机" />
          <el-table-column label="操作" align="center" width="120" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button type="primary" size="small" @click="onAddMember(scope.row)">邀请</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-if="memberType == 1">
        <el-table :data="userList" border style="width: 100%">
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="mobile" label="手机" />
          <el-table-column label="操作" align="center" width="120" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button type="primary" size="small" @click="onAddMember(scope.row)">邀请</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div style="display: flex; justify-content: center; align-items: center; margin-top: 10px;">
        <el-pagination size="small" background layout="prev, pager, next" :total="total" class="mt-4"
          @change="pageChange" />
        <div style="font-size: 12px; margin-left: 10px;">共{{total}}条</div>
      </div>
    </el-dialog>
    <LegalInfo :visible="isVisible" :laId="currnetId" :groupId="groupId" @closeDialog="closeDialog" />
  </div>
</template>
<script lang="ts" setup>
import { ref, onMounted, onUnmounted, watchEffect, withDefaults } from '../../../adapter-vue';
import {
  TUIStore,
  StoreName,
  TUITranslateService,
  IConversationModel,
} from '@tencentcloud/chat-uikit-engine';
import { TUIConstants } from '@tencentcloud/tui-core';
// import { JoinGroupCard } from '@tencentcloud/call-uikit-vue';
import Icon from '../../common/Icon.vue';
import backSVG from '../../../assets/icon/back.svg';
import { isPC } from '../../../utils/env';
import TUIChatConfig from '../config';
import { Chat } from '@/main';
import { getGroupInfo, getLegalList, getUserlList, AddMember, DelMember, addTag } from '@/api';
import LegalInfo from '../../common/LegalInfo/index'

const props = defineProps({
  groupInfo: {
    type: Object,
    default: () => {},
  },
  isNotInGroup: {
    type: Boolean,
    default: false,
  }
});

const emits = defineEmits(['closeChat']);
const currentConversation = ref<IConversationModel>();
const currentConversationName = ref('');
const typingStatus = ref(false);
const groupID = ref('');
const isNotRoomChat = ref<boolean>(TUIChatConfig.getChatType() !== TUIConstants.TUIChat.TYPE.ROOM);
const drawer = ref(false);
const innerDrawer = ref(false);
const innerTitle = ref('');
const groupInfoManager = ref({});
const userInfo = localStorage.getItem('userInfo') ? JSON.parse(localStorage.getItem('userInfo') as string) : {};
const dialogVisible = ref(false);
const legalList = ref([]);
const userList = ref([]);
const page = ref(1);
const total = ref(0);
const memberType = ref(2);
const queryMobile = ref('');
const queryName = ref('');
const tags = ref([]);
const isVisible = ref(false);
const currnetId = ref('')
const groupId = ref('')

onMounted(() => {
  TUIStore.watch(StoreName.CONV, {
    currentConversation: onCurrentConversationUpdated,
  });

  TUIStore.watch(StoreName.CHAT, {
    typingStatus: onTypingStatusUpdated,
  });
});

onUnmounted(() => {
  TUIStore.unwatch(StoreName.CONV, {
    currentConversation: onCurrentConversationUpdated,
  });

  TUIStore.unwatch(StoreName.CHAT, {
    typingStatus: onTypingStatusUpdated,
  });
});

const closeChat = (conversationID: string | undefined) => {
  emits('closeChat', conversationID);
};

const handleExtensions = (e: Event) => {
  // item.listener.onClicked?.({ groupID: groupID.value });
  drawer.value = true;
  getInfo();
};

const openInnerDrawer = (e: Number) => {
  innerDrawer.value = true;
  switch(e) {
    case 1: innerTitle.value = '群成员'; break;
    case 2: innerTitle.value = '群公告'; break;
    case 3: innerTitle.value = '群介绍'; break;
    case 4: innerTitle.value = '群备注'; break;
  }
};

const openAddMember = () => {
  dialogVisible.value = true;
  if (memberType.value == 2) {
    getLaList();
  } else {
    getUList();
  }
};

const onTypeChange = () => {
  page.value = 1;
  if(memberType.value == 2) {
    getLaList();
  } else {
    getUList();
  }
};

const getLaList = () => {
  getLegalList({
    page: page.value,
    GroupId: groupID.value,
    mobile: queryMobile.value,
    name: queryName.value,
  }).then((res: any) => {
    legalList.value = res.data;
    total.value = res.count;
  }).catch((err: any) => {

  })
};

const getUList = () => {
  getUserlList({
    page: page.value,
    GroupId: groupID.value,
    mobile: queryMobile.value,
    name: queryName.value,
  }).then((res: any) => {
    userList.value = res.data;
    total.value = res.count;
  }).catch((err: any) => {

  })
};

const pageChange = (e: number) => {
  page.value = e;
  if (memberType.value == 2) {
    getLaList();
  } else {
    getUList();
  }
};

const onSearch = () => {
  if(queryMobile.value == '' && queryName.value == '') {
    return;
  }
  page.value = 1;
  if(memberType.value == 2) {
    getLaList();
  } else {
    getUList();
  }
};

const onClearSearch = () => {
  queryMobile.value = '';
  queryName.value = '';
  page.value = 1;
  if(memberType.value == 2) {
    getLaList();
  } else {
    getUList();
  }
};

const onAddMember = (item: any) => {
  AddMember({
    GroupId: groupID.value,
    f_user_id: item.id,
    user_type: memberType.value,
    im_id: item.im_id
  }).then((res: any) => {
    dialogVisible.value = false;
    getInfo();
  }).catch((err: any) => {

  })
};

const onDelMember = (item: any) => {
  DelMember({
    GroupId: groupID.value,
    f_user_id: item.f_user_id,
    user_type: memberType.value,
    im_id: item.im_id
  }).then((res: any) => {
    innerDrawer.value = false;
    getInfo();
  }).catch((err: any) => {

  })
};

const getInfo = () => {
  getGroupInfo({
    GroupId: groupID.value,
  }).then((res: any) => {
    let result = res.data;
    result.memberNum = result.member.length
    groupInfoManager.value = result;
  }).catch((err: any) => {

  })
}

function onCurrentConversationUpdated(conversation: IConversationModel) {
  currentConversation.value = conversation;
  groupID.value = currentConversation.value?.groupProfile?.groupID;
  currentConversationName.value = currentConversation?.value?.getShowName();
  if (currentConversation.value.groupProfile.groupCustomField[0].value){
    tags.value = JSON.parse(currentConversation.value.groupProfile.groupCustomField[0].value);
  } else {
    tags.value = [];
  }
}

function onTypingStatusUpdated(status: boolean) {
  typingStatus.value = status;
  if (typingStatus.value) {
    currentConversationName.value = TUITranslateService.t('TUIChat.对方正在输入');
  } else {
    currentConversationName.value = currentConversation.value?.getShowName() || '';
  }
}

function handleDelTag(index: number){
  tags.value.splice(index, 1);
  let value = ''
  let ids = []
  if (tags.value.length > 0) {
    value = JSON.stringify(tags.value);
    ids = tags.value.map((item: any) => item.id)
  }
  //设置群资料自定义字段
  let promise = Chat.updateGroupProfile({
    groupID: currentConversation.value.groupProfile.groupID,
    groupCustomField: [{ key: 'note', value: value }]
  });
  promise.then(function (imResponse) {
    // console.log(imResponse.data.group) // 修改成功后的群组详细资料
  }).catch(function (imError) {
    console.warn('updateGroupProfile error:', imError); // 修改群组资料失败的相关信息
  });
  if (value == '') {
    topConversation(currentConversation.value.conversationID)
    addTag({
      GroupId: currentConversation.value.groupProfile.groupID,
      note_id: ''
    })
  } else {
    addTag({
      GroupId: currentConversation.value.groupProfile.groupID,
      note_id: ids.toString()
    })
  }
}

function topConversation(conversationID: string) {
  let promise = Chat.pinConversation({ conversationID: conversationID, isPinned: false });
  promise.then(function (imResponse) {
  }).catch(function (imError) {
    console.warn('pinConversation error:', imError); // 置顶会话失败的相关信息
  });
}

function openUserProfile(item: any) {
  isVisible.value = true
  currnetId.value = item.im_id
  groupId.value = groupID.value
}

function closeDialog() {
  isVisible.value = false
  currnetId.value = ''
}

</script>
<style lang="scss" scoped>
.chat-header {
  display: flex;
  min-width: 0;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  border-bottom: solid 1px rgb(231, 231, 231);

  &-container {
    display: flex;
    min-width: 0;
    flex-direction: column;
    justify-content: flex-start;
  }

  &-content {
    margin-right: 20px;
    flex: 1;
    font-size: 16px;
    line-height: 30px;
    font-family: PingFangSC-Medium;
    font-weight: 500;
    color: #000;
    letter-spacing: 0;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }

  &-back,
  &-setting {
    width: 27px;
    height: 27px;

    .icon {
      width: 100%;
      height: 100%;
    }
  }
}

.chat-header-h5 {
  &-back {
    display: flex;
    justify-content: center;
    align-items: center;
  }

  &-content{
    margin: 0 20px;
    text-align: center;
  }
}
.no-margin-drawer .el-drawer__container {
  margin: 0 !important;
}
.drawer-header{
  padding: 20px 0;

  .title{
    font-size: 16px;
  }
}

.row{
  padding: 20px 0;
  border-top: solid 1px #eee;
  .title{
    font-size: 14px;
    display: flex;
    justify-content: space-between;

    .title-right{
      display: flex;
      align-items: center;
    }
  }
  .content{
    font-size: 14px;
    color: #666;
    margin-top: 10px;

    .member-list{
      display: flex;

      .member-item{
        display: flex;
        flex-direction: column;
        align-items: center;
        margin-right: 13px;
        width: 40px;
        flex-shrink: 0;

        img {
            width: 40px;
            height: 40px;
            border-radius: 10px;
        }

        span{
          width: 40px;
          font-size: 12px;
          text-overflow: ellipsis;
          overflow: hidden;
          white-space: nowrap;
        }
      }
      .add-member{
        width: 40px;
        height: 40px;
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: #eee;
        border-radius: 10px;
        cursor: pointer;
        flex-shrink: 0;
      }
    }
  }
}
.member-list{
  li{
    padding-bottom: 10px;
    display: flex;
    align-items: center;
    img {
        width: 50px;
        height: 50px;
        border-radius: 50%;
      }
    
      div {
        font-size: 14px;
        margin-left: 10px;
      }
  }
}
.drawer-content{
  font-size: 14px;
  line-height: 24px;
}
</style>
